<template>
  <el-dialog
    :width="width"
    :destroy-on-close="true"
    :close-on-click-modal="false"
    :append-to-body="true"
    :visible.sync="visPermissions"
    :title="`权限配置--${permissionData.entityDisplayName}`"
  >
    <div class="permissionsFormInner">
      <el-tabs tab-position="left">
        <el-tab-pane
          v-for="item in permissionData.groups"
          :key="item.name"
          :label="item.displayName"
        >
          <el-tree
            ref="permissionTree"
            check-strictly
            :data="transformPermissionTree(item.permissions)"
            :props="treeDefaultProps"
            show-checkbox
            default-expand-all
            node-key="name"
            class="permission-tree"
          />
        </el-tab-pane>
      </el-tabs>
    </div>
    <div slot="footer" style="text-align: right">
      <el-button @click="visPermissions = false"> 取消 </el-button>
      <el-button type="primary" @click="confirmPermissions"> 确定 </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getPermissions, updatePermissions } from '@/http/modules/permissions'
export default {
  name: '',
  props: {
    providerName: {
      type: String,
      required: true
    },
    width: {
      type: [String, Number],
      default: '40%'
    }
  },
  data() {
    return {
      visPermissions: false,
      permissionData: {
        entityDisplayName: '',
        groups: []
      },
      treeDefaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  watch: {
    visPermissions(val) {
      const vm = this
      if (!val) {
        vm.$emit('close')
      }
    }
  },
  methods: {
    handleGetPermissions(row) {
      const vm = this
      vm.providerName === 'R'
        ? (vm.providerKey = row.name)
        : (vm.providerKey = row.id)
      getPermissions({
        providerName: vm.providerName,
        providerKey: vm.providerKey
      })
        .then(res => {
          vm.permissionData = res
          vm.visPermissions = true
          for (const i in vm.permissionData.groups) {
            const keys = []
            const group = vm.permissionData.groups[i]
            for (const j in group.permissions) {
              if (group.permissions[j].isGranted) {
                keys.push(group.permissions[j].name)
              }
            }
            vm.$nextTick(() => {
              vm.$refs['permissionTree'][i].setCheckedKeys(keys)
            })
          }
        })
        .catch(err => {
          console.error(err)
        })
    },
    isGrantedByOtherProviderName(grantedProviders) {
      const vm = this
      if (grantedProviders.length) {
        return (
          grantedProviders.findIndex(p => p.providerName !== vm.providerName) >
          -1
        )
      }
      return false
    },
    transformPermissionTree(permissions, name = null) {
      const vm = this
      const arr = []
      if (!permissions || !permissions.some(v => v.parentName === name)) {
        return arr
      }

      const parents = permissions.filter(v => v.parentName === name)
      for (const i in parents) {
        let label = ''
        if (vm.providerName === 'R') {
          label = parents[i].displayName
        } else if (vm.providerName === 'U') {
          label =
            parents[i].displayName +
            ' ' +
            parents[i].grantedProviders.map(provider => {
              return `${provider.providerName}: ${provider.providerKey}`
            })
        }
        arr.push({
          name: parents[i].name,
          label,
          disabled: vm.isGrantedByOtherProviderName(
            parents[i].grantedProviders
          ),
          children: vm.transformPermissionTree(permissions, parents[i].name)
        })
      }
      return arr
    },
    confirmPermissions() {
      const vm = this
      const tempData = []
      for (const i in this.permissionData.groups) {
        const keys = this.$refs['permissionTree'][i].getCheckedKeys()
        const group = this.permissionData.groups[i]
        for (const j in group.permissions) {
          if (
            group.permissions[j].isGranted &&
            !keys.some(v => v === group.permissions[j].name)
          ) {
            tempData.push({
              isGranted: false,
              name: group.permissions[j].name
            })
          } else if (
            !group.permissions[j].isGranted &&
            keys.some(v => v === group.permissions[j].name)
          ) {
            tempData.push({ isGranted: true, name: group.permissions[j].name })
          }
        }
      }
      updatePermissions(
        { providerKey: vm.providerKey, providerName: vm.providerName },
        { permissions: tempData }
      ).then(() => {
        this.visPermissions = false
        this.$notify({
          title: '保存成功',
          message: '角色权限设置成功',
          type: 'success',
          duration: 2000
        })
        // fetchAppConfig(
        //   this.permissionsQuery.providerKey,
        //   this.permissionsQuery.providerName
        // )
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
